//
//  ST_KnighthoodLevelLayout.swift
//  btvideo
//
//  Created by Jason on 2021/8/30.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit

class ST_KnighthoodLevelLayout: UICollectionViewFlowLayout {
    
    
    override func prepare() {
        super.prepare()
        
        scrollDirection = .horizontal
        
        let cellWidth:CGFloat = 62
        minimumLineSpacing = (ScreenWidth - cellWidth * 4)/4
        minimumInteritemSpacing = 0
        let leftEdge = cellWidth*0.5+minimumLineSpacing
        sectionInset = UIEdgeInsets(top: 0, left: leftEdge, bottom: 0, right: leftEdge)
        itemSize = CGSize(width: cellWidth, height: cellWidth+30+25)
        
    }
    
    
    // MARK: 保持Cell每次滑动后停止在UICollectionView的中间
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        // 计算展示Cell的矩形框大小
        var rect = CGRect.init()
        rect.origin.y = 0
        rect.origin.x = proposedContentOffset.x
        rect.size = (self.collectionView?.frame.size)!
        
        var ContentOffset = proposedContentOffset.x
        // 计算CollectionView 中点Cell的偏移的 X 坐标值
        let CollectionViewCenterX = proposedContentOffset.x + (self.collectionView?.frame.width)! * 0.5
        
        var minDelta = MAXFLOAT
        for item:UICollectionViewLayoutAttributes in super.layoutAttributesForElements(in: rect)!{
            if CGFloat(abs(minDelta)) > abs(item.center.x - CollectionViewCenterX) {
                minDelta = Float(item.center.x - CollectionViewCenterX)
            }
        }
        ContentOffset += CGFloat(minDelta)
        return CGPoint.init(x: ContentOffset, y: proposedContentOffset.y)
    }
}
